import { addPosts, deletePosts, getPosts, updatePosts, uploadPosts } from '@/api/posts';
import CommonTable from '@/components/Table';
import React, { useRef, useState } from 'react';
import SearchBar from './Search';
import { Tag } from 'antd';
import { TagsItem } from '@/api/tags';
import { ColumnType } from 'antd/es/table';
import AddForm from './AddForm';
import EditForm from './EditForm';

const defaultColumn: ColumnType<TagsItem>[] = [
  {
    title: '标题',
    key: 'title',
    dataIndex: 'title'
  },
  {
    title: '标签',
    key: 'tags',
    dataIndex: 'tags',
    render: (tags: any) => (tags ? JSON.parse(tags) : []).map((it: string, idx: number) => <Tag key={idx}>{it}</Tag>)
  },
  {
    title: '内容',
    key: 'content',
    dataIndex: 'content',
  },
  {
    title: '用户ID',
    key: 'userID',
    dataIndex: 'userID',
  }
];

export default function PostsManagement() {
  const [tagsData, setTagsData] = useState<TagsItem[]>([]);
  const [recorde, setRecord] = useState<TagsItem>();
  const formRef = useRef();
  const handleChange = (data: TagsItem[]) => setTagsData(data);
  const handleRecordChange = (data: TagsItem, form: any) => {
    setRecord(data);
    formRef.current = form;
  };
  return (
    <>
      <CommonTable
        title="博客"
        deleteApi={deletePosts}
        getDataApi={getPosts}
        updateDataApi={updatePosts}
        uploadApi={uploadPosts}
        addDataApi={addPosts}
        columns={defaultColumn}
        onChange={handleChange}
        onRecordChange={handleRecordChange}
        EditForm={<EditForm data={recorde} form={formRef.current} />}
        SerchBar={<SearchBar />}
      />
    </>
  );
}
